<?php
/**
 * Created by 荣耀电竞.
 * User: 林子彦 <278805354@qq.com>
 * Date: 2018/8/9 0009
 * Time: 15:26
 */

namespace server;

trait WorkerStart
{
    /***
     * 开始phalcon
     * @param $server
     * @param $worker_id
     */
    public function onWorkerStart($server, $worker_id)
    {
        echo __FUNCTION__, PHP_EOL, PHP_EOL;
        define('APP_ROOT', dirname(__DIR__) . '/');
        $this->clearCache();
        $this->phpSetting();
        $this->workerProcessSettting();
        $this->composerAutoload();  //加载composer但前面已加载所以无需
        /**
         * 装载phalcon
         */
        $di = $this->getDi();  //路由，db ,视图，redis 。。。
        $di->httpServer = $this;
        $this->application = new \Phalcon\Mvc\Application($di);
        //注册模型
        //$this->registerModules();
        $this->_taskMgr->initTaskWorker($server, $worker_id);

    }

    private function phpSetting()
    {
        error_reporting(E_ALL);
        ini_set('display_errors', '1');
        //将出错信息输出到一个文本文件
        ini_set('error_log', APP_ROOT . '/storage/logs/php_error_log.txt');
    }

    /**
     * worker process setting
     */
    private function workerProcessSettting()
    {
        if (PHP_OS == 'Linux') {
            $user = posix_getpwnam('nobody');
            posix_setgid($user['gid']);
            posix_setuid($user['uid']);
        }

    }

    /**
     * 返回di设置
     * @return mixed
     */
    public function getDi(){
       return   \App\Base\Helpers\PhalconCiLoader::loadDiConfig();
    }

    private function composerAutoload()
    {
        require dirname(__DIR__) . '/vendor/autoload.php';
    }

    /**
     * 清除opcache 和 apc_cache
     */
    private function clearCache()
    {
        if (function_exists('apc_clear_cache')) {
            apc_clear_cache();
        }
        if (function_exists('opcache_reset')) {
            opcache_reset();
        }
    }

    /**
     * 注册模型...composer 已加载，所以无需在此操作
     */
//    public function registerModules()
//    {
//        // Register the installed modules
//        $this->application->registerModules( array(
//            'Base' =>
//                array(
//                    'className' => 'App\Base\Module',
//                    'path' => APP_ROOT . 'App/Base/Module.php'
//                ),
//            'User' =>
//                array(
//                    'className' => 'App\Base\Module',
//                    'path' => APP_ROOT . 'App/Base/Module.php'
//                )
//        ));
//    }

}